package com.gstaykov.pscoder.editor.handlers;

import java.util.Arrays;
import java.util.Vector;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.CoreException;

import com.gstaykov.pscoder.editor.completion.CompletionDictionary;
import com.gstaykov.pscoder.editor.completion.FileData;
import com.gstaykov.pscoder.util.Logger;
import com.gstaykov.pscoder.util.Util;

public class QuickOutlineHandler extends AbstractHandler {
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		// TODO: find a way to distinguish between Ctrl+0 and Ctr+OO
		
		String[] memberList = getAvailableMembers();
		System.out.println("The members from the active file are: \n");	
		
		for (int i = 0; i < memberList.length; i++) {
			System.out.println(memberList[i] + "\n");			
		}

		memberList = getInheritedMembers();
		System.out.println("The members from inherited files are: \n");	
		
		for (int i = 0; i < memberList.length; i++) {
			System.out.println(memberList[i] + "\n");			
		}

		return null;
	}
	
	public String[] getAvailableMembers() {
		return Util.getFileDataForActiveFile().getMembers();
	}
	
	public String[] getInheritedMembers() {
		FileData activeFileData = Util.getFileDataForActiveFile();
		String[] sourcedFiles = activeFileData.getSourcedFiles();
		
		try {
			CompletionDictionary dict = CompletionDictionary.getInstance(Util.getActiveProject().getName());
			
			Vector<String> membersList = new Vector<String>();
			
			if (sourcedFiles != null && sourcedFiles.length > 0) {
				for (String sourcedFile : sourcedFiles) {
					System.out.println("Processing " + dict.getFullFilenameForEnding(sourcedFile));
					FileData sourcedFileData = dict.getFileData(dict.getFullFilenameForEnding(sourcedFile));
	
					membersList.addAll(Arrays.asList(sourcedFileData.getMembers()));
				}
			}
			
			// FIXME: [IN] Find a better way to cast to String[]?
			return membersList.toArray(new String[]{});
	    } 
		catch (CoreException ce) {
	        Logger.getInstance().logError("Error while trying to get completion dictionary object: \n", ce);
	    }
		
		return null;
	}

}
